﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion;

namespace Abc.Web.Mvc.Areas.HtAdmin.Controllers;

/// <summary>
/// 后台账户管理：登入、登出
/// </summary>
[AllowAnonymous]
public class LoginController : HtAdminBaseController
{
    private readonly IHtAccountService _htAccountService;
    private readonly IDataConfigService _dataConfigService;
    private readonly Lazy.Captcha.Core.ICaptcha _captcha;
    public LoginController(IHtAccountService htAccountService
        , IDataConfigService dataConfigService
,
Lazy.Captcha.Core.ICaptcha captcha)
    {
        _htAccountService = htAccountService;
        _dataConfigService = dataConfigService;
        _captcha = captcha;
    }

    [HttpGet]
    [AllowAnonymous]
    public async Task<ActionResult> Index(string returnUrl)
    {
        ViewBag.returnUrl = returnUrl.LoginReturnUrlVer("/HtAdmin/Home/Index");

        var appinfo = AppEx.GetConfig<AppInfoOptions>();
        //登陆数据加密公钥
        ViewBag.LoginPublicKey = appinfo.HtAdminLoginRsaPublic;

        var dataconfig = await _dataConfigService.GetByKey("CopyrightInformation");

        ViewData["CopyrightInformation"] = dataconfig?.Value ?? "";
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> LoginAsync(HtLoginInput logininput)
    {
        var resultdata = await _htAccountService.Login(logininput);

        return Json(resultdata);
    }

    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> LoginOutToLogin()
    {
        await HttpContext.SignOutAsync(AuthorizeType.AdminAuthenticationScheme);
        return RedirectToAction("Index", "Login", new { area = "HtAdmin" });
    }

    [HttpGet, HttpPost]
    public async Task<JsonResult> LoginOut()
    {
        await HttpContext.SignOutAsync(AuthorizeType.AdminAuthenticationScheme);
        //  return RedirectToAction("Login", "Account", new { area = "HtAdmin" });
        return Json(new { succeeded = true });
    }

    //[UnifyResult(typeof(JsonResult))]
    //[HttpGet]
    //[AllowAnonymous]
    //public IActionResult GetVerifyCode()
    //{
    //    var imgbyte = CaptchaHelper.GetVerifyCode(out string verCode, verifyKey: "HtAdmin");
    //    return File(imgbyte.ToArray(), @"image/png");
    //}

    [UnifyResult(typeof(JsonResult))]
    [HttpGet]
    [AllowAnonymous]
    public IActionResult GetVerifyCode()
    {
        //生成唯一标识
        var id = Guid.NewGuid().ToString();
        App.HttpContext.SetSession("HtAdmin", id);


        var info = _captcha.Generate(id);
        var stream = new MemoryStream(info.Bytes);
        return File(stream, "image/gif");
    }
}